﻿// This script builds a ClickOnce package for upload to CodePlex. It expects to find files in bin/Release.

#I @"..\packages\DotNetZip.1.9.1.8\lib\net20"
#r "Ionic.Zip.dll"

open System
open System.IO
open System.Diagnostics
open System.Reflection
open Ionic.Zip

let (@@) a b = Path.Combine(a, b)

let compilePath = @".\bin\Release"
let magePath    = @"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\mage.exe"

if not <| File.Exists(compilePath @@ "CoffeeMonitor.exe") then
    failwith "Output files not found. Please do a Release build first."

printfn "Building ClickOnce deployment package..."

let version =
    let assem = Assembly.ReflectionOnlyLoadFrom(compilePath @@ "CoffeeMonitor.exe")
    assem.GetName().Version

let deployFiles =
    Directory.EnumerateFiles(compilePath)
    |> Seq.filter (Path.GetExtension >> 
                   function ".exe" | ".dll" | ".config" | ".ico" -> true | _ -> false)
    |> List.ofSeq

let versionFolder = sprintf "CoffeeMonitor_%i_%i_%i_%i" version.Major version.Minor version.Build version.Revision
let appPath = compilePath @@ "Application Files"
let deployPath = appPath @@ versionFolder
let manifest = "CoffeeMonitor.exe.manifest"
let application = "CoffeeMonitor.application"

if Directory.Exists appPath then
    Directory.Delete(appPath, true)

Directory.CreateDirectory(appPath)
Directory.CreateDirectory(deployPath)

// rename the output files to have a ".deploy" extension
deployFiles |> List.iter (fun f -> File.Move(f, deployPath @@ (Path.GetFileName(f))))

let runMage args =
    let pi = ProcessStartInfo(FileName = magePath, Arguments = args, 
                              RedirectStandardOutput = true, RedirectStandardError = true, 
                              UseShellExecute = false)
    use proc = Process.Start(pi)
    printf "%s" <| proc.StandardOutput.ReadToEnd()
    proc.WaitForExit()
    if proc.ExitCode <> 0 then
        failwith "Mage.exe error!"

// create the manifest file
sprintf "-New Application -ToFile \"%s\" -Version %O -FromDirectory \"%s\" -IconFile \"CoffeeMonitor.ico\" -Processor x86 -CertFile ClickOnce.pfx" 
        (deployPath @@ manifest) version deployPath
|> runMage

// update the application file
sprintf "-Update \"%s\" -Version %O -appc \"%s\" -appm \"%s\" -SupportUrl \"http://coffeemonitor.codeplex.com/\" -Processor x86 -CertFile ClickOnce.pfx"
        (compilePath @@ application) version ("Application Files" @@ versionFolder @@ manifest) (deployPath @@ manifest)
|> runMage

if File.Exists(compilePath @@ "Deploy.zip") then
    File.Delete(compilePath @@ "Deploy.zip")

let zip = new ZipFile(compilePath @@ "Deploy.zip")
try
    zip.AddFile(compilePath @@ application, "") |> ignore
    zip.AddDirectory(appPath, "Application Files") |> ignore
    zip.Save()
finally
    zip.Dispose()

printfn "Wrote ClickOnce package to: %s" (compilePath @@ "Deploy.zip")


